﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Models
{
    /// <summary>
    /// OA 接口参数转码
    /// </summary>
    public static class EncodingHelper
    {
        #region 转化为标准UTF8字符Base64编码
        /// <summary>
        /// 转化为标准UTF8字符Base64编码
        /// </summary>
        /// <param name="strCode">待转化字符串</param>
        /// <returns></returns>
        public static string ToUtf8Base64(this string strCode)
        {
            if (string.IsNullOrEmpty(strCode)) return "";
            var bytes = Encoding.UTF8.GetBytes(strCode);
            return (Convert.ToBase64String(bytes));
        }
        #endregion

        #region 转化为标准字符串
        /// <summary>
        /// 转化为标准字符串
        /// </summary>
        /// <param name="strCode"></param>
        /// <returns></returns>
        public static string FromUtf8Base64(this string strCode)
        {
            if (string.IsNullOrEmpty(strCode)) return "";
            byte[] outputb = Convert.FromBase64String(strCode);
            return(Encoding.UTF8.GetString(outputb));
        }
        #endregion

        #region 把对象属性值转为UTF8 Base64编码
        /// <summary>
        /// 把对象属性值转为UTF8 Base64编码
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T ToUtf8Base64ObjectValues<T>(this T obj)
        {
            //得到对象的类型
            var type = obj.GetType();
            //得到字段的值,只能得到public类型的字典的值
            var fieldInfos = type.GetProperties();
            // 批量对字段的指转码为正常字符
            foreach (var f in fieldInfos)
            {
                //字段的值
                var fieldValue = f.GetValue(obj, null) == null ? null : f.GetValue(obj, null).ToString();
                //转码
                f.SetValue(obj, fieldValue.ToUtf8Base64(), null);
            }
            return obj;
        }
        #endregion

        #region 把对象属性值转为正常字符
        /// <summary>
        /// 把对象属性值转为正常字符
        /// </summary>
        /// <param name="obj"></param>
        public static T FromUtf8Base64ObjectValues<T>(this T obj)
        {
            //得到对象的类型
            var type = obj.GetType();
            //得到字段的值,只能得到public类型的字典的值
            var fieldInfos = type.GetProperties();
            // 批量对字段的指转码为正常字符
            foreach (var f in fieldInfos)
            {
                //字段的值
                var fieldValue = f.GetValue(obj, null) == null ? null : f.GetValue(obj, null).ToString();
                //转码
                f.SetValue(obj, fieldValue.FromUtf8Base64(),null);
            }
            return obj;
        }
       #endregion
    }
}
